package com.secsbrain.development.biz.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.secsbrain.sso.core.SsoHelper;
import com.secsbrain.development.dal.mapper.DeployPlanMapper;
import com.secsbrain.development.dal.model.ProjectApp;
import com.secsbrain.development.web.dto.PublishProjectDTO;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.secsbrain.development.dal.model.DeployPlan;

import com.secsbrain.development.biz.IDeployPlanService;
import com.secsbrain.development.biz.IProjectAppService;
import com.baomidou.framework.service.impl.SuperServiceImpl;
import com.baomidou.mybatisplus.plugins.Page;

/**
 *
 * DeployPlan 表数据服务层接口实现类
 *
 */
@Service
public class DeployPlanServiceImpl extends SuperServiceImpl<DeployPlanMapper, DeployPlan> implements IDeployPlanService {

	@Autowired
	IProjectAppService projectAppService;
	
	/* (non-Javadoc)
	 * @see IDeployPlanService#queryDeployPlanList(com.baomidou.mybatisplus.plugins.Page, DeployPlan)
	 */
	@Override
	public Page<DeployPlan> queryDeployPlanList(Page<DeployPlan> page, DeployPlan deployPlan) {
		page.setRecords(this.baseMapper.queryDeployPlanList(page, deployPlan));
		return page;
	}

	/* (non-Javadoc)
	 * @see IDeployPlanService#saveOrUpdateDeployPlan(PublishProjectDTO)
	 */
	@Override
	@Transactional
	public void saveOrUpdateDeployPlan(PublishProjectDTO publishProjectDTO) {
		if (publishProjectDTO.getId() != null && publishProjectDTO.getId() > 0) {
			DeployPlan deployPlanUp=new DeployPlan();
			deployPlanUp.setId(publishProjectDTO.getId());
			deployPlanUp.setBuildDes(publishProjectDTO.getProjectDesc());
			deployPlanUp.setUpdateName(SsoHelper.currentUser().getRealName());
			deployPlanUp.setUpdateTime(new Date());
			this.updateSelectiveById(deployPlanUp);
			
			ProjectApp projectAppDel=new ProjectApp();
			projectAppDel.setProjectId(publishProjectDTO.getId());
			projectAppService.deleteSelective(projectAppDel);
			
			if(CollectionUtils.isNotEmpty(publishProjectDTO.getAppList())){
				List<ProjectApp> projectAppList=new ArrayList<ProjectApp>();
				for(PublishProjectDTO.AppInfo appInfo:publishProjectDTO.getAppList()){
					ProjectApp projectApp=new ProjectApp();
					projectApp.setAppBranch(appInfo.getBranch());
					projectApp.setAppId(appInfo.getId());
					projectApp.setAppName(appInfo.getAppName());
					projectApp.setCreatedTime(new Date());
					projectApp.setProjectId(publishProjectDTO.getId());
					
					projectAppList.add(projectApp);
				}
				projectAppService.insertBatch(projectAppList);
			}
        } else {
            //TODO  新增暂时不支持
        }
	}

}